package com.java110.mall.chain.supplier.adaper.llk;

import com.alibaba.fastjson.JSONObject;
import com.java110.core.client.RestTemplate;
import com.java110.dto.chain.ChainSupplierDto;
import com.java110.utils.log.LoggerEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;

public class LlkFactory {

    private final static Logger logger = LoggerFactory.getLogger(LoggerEngine.class);

    /**
     * 刷入sign
     * @param param
     */
    public static void createSign(JSONObject param){
        String sign = Md5Util.encrypt(param.get("encryptedData").toString() + param.get("channelId").toString() + param.get("timestamp").toString());
        param.put("sign",sign);
    }


    public static JSONObject getData(JSONObject reqParam, ChainSupplierDto chainSupplierDto){
        JSONObject data = new JSONObject();
        data.put("channelId",chainSupplierDto.getAppId());
        data.put("timestamp",System.currentTimeMillis());
        data.put("encryptedData",AesUtils.aesEncrypt(reqParam.toJSONString(),chainSupplierDto.getAppSecure()));
        createSign(data);
        return data;
    }

    public static String post(String url,JSONObject reqParam,ChainSupplierDto chainSupplierDto, RestTemplate outRestTemplate){
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type","application/json;charset=utf-8");
        logger.debug("接口查询参数 ，{}", reqParam);
        HttpEntity httpEntity = new HttpEntity(LlkFactory.getData(reqParam,chainSupplierDto).toJSONString(),headers);
        ResponseEntity<String> _paramOut = outRestTemplate.exchange(chainSupplierDto.getUrl()+url, HttpMethod.POST, httpEntity,String.class);
        logger.debug("返回信息 ，{}", _paramOut);
        System.out.println(_paramOut);
        JSONObject paramOut = JSONObject.parseObject(_paramOut.getBody());
        if(paramOut.getInteger("code") != 200){
            throw new IllegalArgumentException(paramOut.getString("message "));
        }
        //验证签名
        JSONObject data = paramOut.getJSONObject("data");
        //签名加密
        String sign = Md5Util.encrypt(data.getString("encryptedData") + data.get("timestamp").toString());
        if(!sign.equals(data.getString("sign"))){
            throw new IllegalArgumentException("签名失败"+paramOut);
        }
        String resData = AesUtils.aesDecrypt(data.getString("encryptedData"), chainSupplierDto.getAppSecure());
        return resData;
    }



}
